package com.dhcc.wb.articleliushui;

import java.util.List;
import java.util.UUID;

import org.json.JSONObject;

import com.dhcc.common.util.StringUtil;
import com.dhcc.wb.gongzhonghao.GzhDao;
import com.dhcc.wb.gongzhonghao.GzhModel;
import com.dhcc.wb.util.HttpUtil;
import com.dhcc.wb.util.TokenUtil;
import com.google.gson.Gson;

/**
 * @author wb
 *
 */
public class ArticleLiushuiTask{
	
	private static String getarticletotalUrl = "https://api.weixin.qq.com/datacube/getarticletotal?access_token=";//获取图文群发每日数据


	
	//循环所有公众号文章
	public static void updateArticle(String begin_date,String end_date){
		GzhDao gzhdao = new GzhDao();
		List<GzhModel> gzhlist = gzhdao.getAll();
		if(gzhlist != null && gzhlist.size()>0){
			for(GzhModel gzh :gzhlist){
				updateSingleArticle(gzh.getGzhid(),begin_date,end_date,gzh.getGzhname());
			}
		}
	}
	
	
	/**
	 * 更新一个公众号文章
	 * begin_date end_date 最大时间跨度 1
	 * 获取的是 这个时间段群发的文章    截止到当前日期的总阅读量
	 * 
	 * 统计的日期，在getarticletotal接口中，ref_date指的是文章群发出日期， 而stat_date是数据统计日期
	 * begin end 群发的文章 到当前日期 每天的统计量
	 */
	public static void updateSingleArticle(String gzhid,String begin_date,String end_date,String gzhname){
		try {
			String token = TokenUtil.getToken(gzhid);
			if(!StringUtil.isNullOrEmpty(token)){
				JSONObject json = new JSONObject();
				json.put("begin_date", begin_date);
				json.put("end_date", end_date);
				String content1 = HttpUtil.postContent(getarticletotalUrl+token, json.toString());
				Gson gson2 = new Gson();
				ArticleLiushuiModel articleList = gson2.fromJson(content1, ArticleLiushuiModel.class);
				
				ArticleLiushuiDao dao = new ArticleLiushuiDao();
				if(articleList != null && articleList.getList() != null && articleList.getList().size()>0){
					for(Article2Model ent:articleList.getList()){
						if(ent.getDetails() != null && ent.getDetails().size()>0){
							for(ArticleDetailsModel detail : ent.getDetails()){
								ArticleDetailsModel art = dao.queryArticle_result(ent.getTitle(), ent.getMsgid(),detail.getStat_date(),gzhid);
								if(art == null){
									dao.addArticleLiushui(UUID.randomUUID().toString(), gzhid,gzhname, ent.getRef_date(), ent.getMsgid(), ent.getTitle(),detail.getStat_date(), 
											detail.getInt_page_read_user(),detail.getInt_page_read_count(), detail.getOri_page_read_user(), detail.getOri_page_read_count(), 
											detail.getShare_user(), detail.getShare_count(), detail.getAdd_to_fav_user(), detail.getAdd_to_fav_count());
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
	}
	

    public static void main(String[] args) {
//    	updateArticle("2019-11-13","2019-11-13");
    	
    	
    	
    	
    	
	}
		
		
	
}
